<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="操作日志">
        记录所有用户操作的详细日志信息，支持按时间、用户、操作类型等条件查询。
      </n-card>
    </div>
    <n-card :bordered="false" title="操作日志列表" class="mt-4">
      <n-space vertical :size="16">
        <!-- 搜索栏 -->
        <n-space justify="space-between">
          <n-space>
            <n-input
              v-model:value="searchParams.keyword"
              placeholder="请输入用户姓名或操作内容"
              style="width: 300px"
              clearable
            />
            <n-select
              v-model:value="searchParams.operationType"
              placeholder="操作类型筛选"
              :options="operationTypeOptions"
              style="width: 150px"
              clearable
            />
            <n-select
              v-model:value="searchParams.module"
              placeholder="功能模块筛选"
              :options="moduleOptions"
              style="width: 150px"
              clearable
            />
            <n-date-picker
              v-model:value="searchParams.dateRange"
              type="daterange"
              placeholder="选择时间范围"
              style="width: 300px"
              clearable
            />
            <n-button type="primary" @click="handleSearch">
              <template #icon>
                <n-icon>
                  <SearchOutline />
                </n-icon>
              </template>
              搜索
            </n-button>
            <n-button @click="handleReset">重置</n-button>
          </n-space>
          <n-space>
            <n-button @click="handleExport">
              <template #icon>
                <n-icon>
                  <DownloadOutline />
                </n-icon>
              </template>
              导出日志
            </n-button>
            <n-button @click="handleCleanup" type="warning">
              <template #icon>
                <n-icon>
                  <TrashOutline />
                </n-icon>
              </template>
              清理日志
            </n-button>
          </n-space>
        </n-space>

        <!-- 数据表格 -->
        <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :pagination="pagination"
          :row-key="rowKey"
          @update:page="handlePageChange"
        />
      </n-space>
    </n-card>

    <!-- 日志详情抽屉 -->
    <n-drawer v-model:show="showDetail" :width="800" placement="right">
      <n-drawer-content title="操作日志详情" closable>
        <n-descriptions :column="1" bordered v-if="currentLog">
          <n-descriptions-item label="操作ID">{{ currentLog.id }}</n-descriptions-item>
          <n-descriptions-item label="用户姓名">{{ currentLog.userName }}</n-descriptions-item>
          <n-descriptions-item label="用户工号">{{ currentLog.userCode }}</n-descriptions-item>
          <n-descriptions-item label="操作类型">
            <n-tag :type="getOperationTypeColor(currentLog.operationType)">
              {{ currentLog.operationType }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="功能模块">{{ currentLog.module }}</n-descriptions-item>
          <n-descriptions-item label="操作内容">{{ currentLog.content }}</n-descriptions-item>
          <n-descriptions-item label="操作时间">{{ currentLog.operationTime }}</n-descriptions-item>
          <n-descriptions-item label="IP地址">{{ currentLog.ipAddress }}</n-descriptions-item>
          <n-descriptions-item label="用户代理">{{ currentLog.userAgent }}</n-descriptions-item>
          <n-descriptions-item label="操作结果">
            <n-tag :type="currentLog.status === 'success' ? 'success' : 'error'">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="耗时">{{ currentLog.duration }}ms</n-descriptions-item>
        </n-descriptions>
        
        <n-divider title-placement="left">请求参数</n-divider>
        <n-code :code="currentLog.requestParams" language="json" />
        
        <n-divider title-placement="left">响应数据</n-divider>
        <n-code :code="currentLog.responseData" language="json" />
        
        <n-divider title-placement="left">错误信息</n-divider>
        <n-alert 
          v-if="currentLog.errorMessage" 
          type="error" 
          :title="currentLog.errorMessage"
        />
        <n-text v-else depth="3">无错误信息</n-text>
      </n-drawer-content>
    </n-drawer>

    <!-- 清理日志确认对话框 -->
    <n-modal v-model:show="showCleanupModal" preset="dialog" title="清理日志">
      <div>
        <n-alert type="warning" title="警告" style="margin-bottom: 16px">
          此操作将永久删除选定时间范围内的日志数据，无法恢复！
        </n-alert>
        <n-form :model="cleanupForm" label-placement="left" :label-width="100">
          <n-form-item label="清理范围">
            <n-radio-group v-model:value="cleanupForm.type">
              <n-space direction="vertical">
                <n-radio value="days">保留最近N天的日志</n-radio>
                <n-radio value="range">清理指定时间范围的日志</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
          <n-form-item label="保留天数" v-if="cleanupForm.type === 'days'">
            <n-input-number v-model:value="cleanupForm.days" :min="1" :max="365" />
          </n-form-item>
          <n-form-item label="时间范围" v-if="cleanupForm.type === 'range'">
            <n-date-picker
              v-model:value="cleanupForm.dateRange"
              type="daterange"
              placeholder="选择要清理的时间范围"
            />
          </n-form-item>
        </n-form>
      </div>
      <template #action>
        <n-space>
          <n-button @click="showCleanupModal = false">取消</n-button>
          <n-button type="error" :loading="cleanupLoading" @click="handleConfirmCleanup">
            确认清理
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, h, computed } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import {
  SearchOutline,
  DownloadOutline,
  TrashOutline,
  EyeOutline,
} from '@vicons/ionicons5';
import { createIndexColumn } from '@/utils/tableUtil';

const message = useMessage();
const dialog = useDialog();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  operationType: null as string | null,
  module: null as string | null,
  dateRange: null as [number, number] | null,
});

// 选项数据
const operationTypeOptions = [
  { label: '新增', value: '新增' },
  { label: '修改', value: '修改' },
  { label: '删除', value: '删除' },
  { label: '查询', value: '查询' },
  { label: '登录', value: '登录' },
  { label: '登出', value: '登出' },
  { label: '授权', value: '授权' },
      { label: '撤销', value: '撤销' },
];

const moduleOptions = [
  { label: '专家库管理', value: '专家库管理' },
  { label: '专家管理', value: '专家管理' },
  { label: '会议管理', value: '会议管理' },
  { label: '权限管理', value: '权限管理' },
  { label: '系统设置', value: '系统设置' },
  { label: '模板管理', value: '模板管理' },
];

// 表格数据
const loading = ref(false);
const tableData = ref<any[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageCount: 0,
  onChange: (page: number) => {
    pagination.page = page;
    loadData();
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
    loadData();
  },
});

// 表格列定义
const columns = computed(() => [
  createIndexColumn({
    currentPage: pagination.page,
    pageSize: pagination.pageSize,
  }),
  { title: '操作时间', key: 'operationTime', width: 180 },
  { title: '用户姓名', key: 'userName', width: 100 },
  { title: '操作类型', key: 'operationType', width: 100 },
  { title: '功能模块', key: 'module', width: 120 },
  { title: '操作内容', key: 'content', ellipsis: true },
  { title: 'IP地址', key: 'ipAddress', width: 140 },
  { title: '状态', key: 'status', width: 80 },
  { title: '耗时', key: 'duration', width: 80 },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    render: (row: any) => {
      return h(
        'n-button',
        {
          size: 'small',
          type: 'info',
          ghost: true,
          onClick: () => handleViewDetail(row),
        },
        { default: () => '详情' }
      );
    },
  },
]);

// 日志详情
const showDetail = ref(false);
const currentLog = ref<any>(null);

// 清理日志
const showCleanupModal = ref(false);
const cleanupLoading = ref(false);
const cleanupForm = reactive({
  type: 'days',
  days: 30,
  dateRange: null as [number, number] | null,
});

// 方法
const rowKey = (row: any) => row.id;

const getOperationTypeColor = (type: string) => {
  const colorMap: Record<string, 'default' | 'error' | 'primary' | 'info' | 'success' | 'warning'> = {
    '新增': 'success',
    '修改': 'warning',
    '删除': 'error',
    '查询': 'info',
    '登录': 'success',
    '登出': 'default',
    '授权': 'success',
    '撤销': 'error',
  };
  return colorMap[type] || 'default';
};

const loadData = () => {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        userName: '张三',
        userCode: 'EMP001',
        operationType: '登录',
        module: '系统管理',
        content: '用户登录系统',
        operationTime: '2024-01-20 09:30:15',
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 1250,
        requestParams: '{"username": "zhangsan", "loginType": "password"}',
        responseData: '{"code": 200, "message": "登录成功", "token": "abc123..."}',
        errorMessage: '',
      },
      {
        id: '2',
        userName: '张三',
        userCode: 'EMP001',
        operationType: '新增',
        module: '专家管理',
        content: '新增专家信息：李教授',
        operationTime: '2024-01-20 10:15:30',
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 856,
        requestParams: '{"name": "李教授", "title": "教授", "department": "计算机学院"}',
        responseData: '{"code": 200, "message": "新增成功", "id": "EXP001"}',
        errorMessage: '',
      },
      {
        id: '3',
        userName: '李四',
        userCode: 'EMP002',
        operationType: '修改',
        module: '专家库管理',
        content: '修改专家库信息：计算机科学专家库',
        operationTime: '2024-01-20 11:22:45',
        ipAddress: '192.168.1.101',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 654,
        requestParams: '{"id": "1", "name": "计算机科学专家库", "description": "更新描述"}',
        responseData: '{"code": 200, "message": "修改成功"}',
        errorMessage: '',
      },
      {
        id: '4',
        userName: '王五',
        userCode: 'EMP003',
        operationType: '删除',
        module: '会议管理',
        content: '删除会议记录：2024年度评审会议',
        operationTime: '2024-01-20 14:30:10',
        ipAddress: '192.168.1.102',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'failed',
        duration: 1025,
        requestParams: '{"meetingId": "MTG001"}',
        responseData: '{"code": 500, "message": "删除失败"}',
        errorMessage: '该会议已关联专家信息，无法删除',
      },
      {
        id: '5',
        userName: '赵六',
        userCode: 'EMP004',
        operationType: '授权',
        module: '权限管理',
        content: '为用户钱七授权专家库管理员权限',
        operationTime: '2024-01-20 15:45:20',
        ipAddress: '192.168.1.103',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 432,
        requestParams: '{"userId": "EMP005", "expertPoolId": "1", "role": "admin"}',
        responseData: '{"code": 200, "message": "授权成功"}',
        errorMessage: '',
      },
      {
        id: '6',
        userName: '钱七',
        userCode: 'EMP005',
        operationType: '查询',
        module: '专家管理',
        content: '查询专家列表',
        operationTime: '2024-01-20 16:10:35',
        ipAddress: '192.168.1.104',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 234,
        requestParams: '{"page": 1, "pageSize": 10, "keyword": ""}',
        responseData: '{"code": 200, "data": {...}, "total": 25}',
        errorMessage: '',
      },
    ];
    pagination.pageCount = Math.ceil(100 / pagination.pageSize); // 模拟总数100条
    loading.value = false;
  }, 500);
};

const handleSearch = () => {
  pagination.page = 1;
  loadData();
};

const handleReset = () => {
  searchParams.keyword = '';
  searchParams.operationType = null;
  searchParams.module = null;
  searchParams.dateRange = null;
  pagination.page = 1;
  loadData();
};

const handlePageChange = (page: number) => {
  pagination.page = page;
  loadData();
};

const handleViewDetail = (row: any) => {
  currentLog.value = row;
  showDetail.value = true;
};

const handleExport = () => {
  message.info('导出功能开发中...');
};

const handleCleanup = () => {
  Object.assign(cleanupForm, {
    type: 'days',
    days: 30,
    dateRange: null,
  });
  showCleanupModal.value = true;
};

const handleConfirmCleanup = () => {
  cleanupLoading.value = true;
  setTimeout(() => {
    message.success('日志清理成功');
    showCleanupModal.value = false;
    cleanupLoading.value = false;
    loadData();
  }, 2000);
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.n-layout-page-header {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
</style> 